import {
  Injectable,
  CanActivate,
  ExecutionContext,
  HttpException,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { Admin } from '../entity/admin.entity';

@Injectable()
export class AdminGuard implements CanActivate {
  async canActivate(context: ExecutionContext) {
    const request = context.switchToHttp().getRequest();
    let token = request.headers.token;
    if (token) {
      // 解析token
      let data = new JwtService().decode(token);
      let now = new Date().getTime() / 1000;
      if (now > Number(data.iat) + 60 * 60 * 24) {
        throw new HttpException('token已过期', 202);
      }

      if (data.id) {
        request.uid = data.id;
        if (data.id == 1) {
          return true;
        }
        let admin = await Admin.findOne({
          where: { id: data.id },
          relations: ['permissions'],
        });
        if (admin.permissions.length == 0) {
          throw new HttpException('您没有操作权限', 202);
        }

        let hasPermission = false;

        admin.permissions.map((item) => {
          if (item.path == request.path && item.method == request.method) {
            hasPermission = true;
          } else if (
            request.path.includes(item.path) &&
            item.method == request.method
          ) {
            hasPermission = true;
          }
        });

        if (hasPermission) {
          return true;
        } else {
          throw new HttpException('您没有操作权限', 400);
        }
      } else {
        return false;
      }
    } else {
      throw new HttpException('请登录', 202);
    }
  }
}
